package com.ws.config;

import com.ws.domain.User;
import com.ws.service.CartsService;
import com.ws.service.TypesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

public class IndexInterceptor  extends HandlerInterceptorAdapter {
    @Autowired
    private TypesService typesService;
    @Autowired
    private CartsService cartsService;

    /*
     * 访问前台功能之前需要进行权限控制。
     * */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        /*
         * 1. 在拦截器中就把typeList查出保存在request中，后面的控制器就不用查了，直接用。
         * 	      因为前台很多的页面都用到
         * */
        request.setAttribute("typeList", typesService.typeList());


        //2. 跟购物车、订单有关的操作必须登录。如果没登录，就去登录，不放行。
        String uri = request.getRequestURI();
        if(uri.contains("index/cart") || uri.contains("index/order") || uri.contains("index/my")) {
            Object user = request.getSession().getAttribute("user");
            if (Objects.isNull(user)) {
                response.sendRedirect("login");
                return false;
            }

        }

        // 3.其他的操作都放行。
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

        //凡是访问购物车的操作，都需要在访问后把购物车的商品数量总和重新查询并更新。
        //1.拦截指定路径
        String uri = request.getRequestURI();

        //2.购物车相关请求后 更新session里面的购物数量。
        if(uri.contains("index/cart")) {
            User user = (User) request.getSession().getAttribute("user");
            request.getSession().setAttribute("cartCount", cartsService.getCount(user.getId()));
        }
    }
}
